package com.atguigu.eduservice.service.impl;

import com.atguigu.eduservice.entity.EduChapter;
import com.atguigu.eduservice.entity.EduVideo;
import com.atguigu.eduservice.entity.vo.chapter.ChapterVo;
import com.atguigu.eduservice.entity.vo.chapter.VideoVo;
import com.atguigu.eduservice.mapper.EduChapterMapper;
import com.atguigu.eduservice.service.EduChapterService;
import com.atguigu.eduservice.service.EduVideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Cyrus
 * @since 2020-12-08
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService eduVideoService;

    @Override
    public List<ChapterVo> getChapterVideo(String courseId) {
        List<EduChapter> eduChapters = baseMapper.selectList(new QueryWrapper<EduChapter>().lambda().eq(EduChapter::getCourseId, courseId));
        ArrayList<ChapterVo> ChapterVoArrayList = new ArrayList<>(); //所有章节的封装
        for (EduChapter eduChapter : eduChapters) {
            ChapterVo chapterVo = new ChapterVo();
            BeanUtils.copyProperties(eduChapter,chapterVo);
            ChapterVoArrayList.add(chapterVo);
            List<EduVideo> eduVideos = eduVideoService.list(new QueryWrapper<EduVideo>().lambda().eq(EduVideo::getChapterId, eduChapter.getId()).eq(EduVideo::getCourseId, eduChapter.getCourseId()));
            ArrayList<VideoVo> VideoVoArrayList = new ArrayList<>();    //所有章节的小结封装
            for (EduVideo eduVideo : eduVideos) {
                VideoVo videoVo = new VideoVo();
                BeanUtils.copyProperties(eduVideo,videoVo);
                VideoVoArrayList.add(videoVo);
            }
            chapterVo.setChildren(VideoVoArrayList);
        }

        return ChapterVoArrayList;
    }


    @Override
    public int deleteChapter(String chapterId) {
        int count = eduVideoService.count(new QueryWrapper<EduVideo>().lambda().eq(EduVideo::getChapterId, chapterId));
        if (count > 0) {
            throw new GuliException(20001, "当前课程中存在小节,请先删除小节再进行此操作");

        } else {
            int result = baseMapper.deleteById(chapterId);
            return result;
        }
    }
}
